//计算总体的金额
var calcalateAll = function () {
    var totalPrice = 0;
    var totalNum = 0;
    $('#itemDetails tr').each(function () {
        var subtotal = 0;
        var row = $(this);
        var tdArr = row.find('td');
        var price = tdArr.eq(3).text();
        var goodnum = tdArr.eq(5).find('input[name="good_num"]').eq(0).val();
        if (!/[1-9]\d*/.test(goodnum)) {
            tdArr.eq(5).find('input[name="good_num"]').eq(0).val(1);
            subtotal += parseFloat(price);
        } else {
            subtotal += (parseFloat(price) * parseFloat(goodnum));
        }
        totalPrice += subtotal;
    });
    console.log('totalPrice:', totalPrice);
    $('#price_sum').html(parseFloat(totalPrice).toFixed(2));
};

var changeMonthPlanName = function () {
    var currentYear = $('#year').val();
    var departmentName = $('#departmentName').val();
    var month = $('#month').val();
    $('#monthplanName').val(currentYear + '年' + departmentName + ' ' + month + '月计划');
};

$(document).ready(function () {
    changeMonthPlanName();
    //加载相关的初始信息
    (function () {
        //改变月度计划
        $('#month').change(function () {
            changeMonthPlanName();
        });
    })();
    //添加事件添加明细
    $('#addItemsBtn').click(function () {
        tipsWindown(
            '添加月度明细',
                'url:get?' + baseUrl + 'monthplans/choosegood?year=' + $('#year').val() + '&departmentId=' + $('#departmentId').val() + '&t=' + new Date().getTime(),
            '1025',
            '700',
            'true',
            '',
            'true',
            'text',
            '');
    });

    //分页处理 ajax 处理
    jQuery("#windown-content .pagination a").live('click', function (e) {
        stopDefault(e);
        var DP_RUL = jQuery(this).attr("href")
        console.log('DP_RUL:', DP_RUL);
        jQuery("#windown-content").load(DP_RUL, {
            'searchGoodName': $('#searchGoodName').val(),
            'categoryId': $('#categoryId').val(),
            't': new Date().getTime()
        });
    });

    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $("#searchBtn").trigger("click");
        }
    });

    $('#returnBtn').click(function () {
        window.location.href = '/monthplans';
    });

    //查询的选择
    $('#searchBtn').live('click', function () {
        var DP_RUL = '/monthplans/choosegood'
        jQuery("#windown-content").load(DP_RUL, {
            'searchGoodName': $('#searchGoodName').val(),
            'year': $('#year').val(),
            'month': $('#month').val(),
            'departmentId': $('#departmentId').val(),
            'categoryId': $('#categoryId').val(),
            't': new Date().getTime()
        });
    });

    $('#categoryId').live('change', function () {
        $("#searchBtn").trigger("click");
    });

    $('#applyBtn').click(function () {
        var priceSum = $('#price_sum').text();
        if (parseFloat(priceSum) > 0) {
            if (confirm('您确定提交审核吗?')) {
                $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "/monthplans/applyMonthPlan",
                    data: {
                        'monthPlanId': $('#monthPlanId').val(),
                        't': new Date().getTime(),
                        'status': 1
                    },
                    success: function (msg) {
                        if (msg.code == '0') {
                            alert('提交成功!');
                            window.location.reload(true);
                        }
                        if (msg.code == '-1') {
                            alert('系统异常，请联系开发者..');
                            return;
                        }
                    }
                });
            }
        }
    });

    function stopDefault(e) {
        // Prevent the default browser action (W3C)
        if (e && e.preventDefault) {
            e.preventDefault();
            // A shortcut for stoping the browser action in IE
        }
        else {
            window.event.returnValue = false;
        }
        return false;
    }

    $('#choosegoodBody a[class="btn-buy"]').live('click', function () {
        //组合相关的数据
        var commbinObj = {};
        var attributeArr = ['goodid', 'goodName', 'goodCode', 'goodSpec', 'goodUnit' , 'goodPrice'];
        for (var i = 0; i < attributeArr.length; i++) {
            var attributeName = attributeArr[i];
            //动态添加属性
            if (attributeName == 'goodPrice') {
                commbinObj[attributeName] = parseFloat($(this).attr(attributeName)).toFixed(2);
            } else {
                commbinObj[attributeName] = $(this).attr(attributeName);
            }
        }
        renderItems(commbinObj);
    });

    var renderItems = function (combineObj) {
        var goodid = combineObj.goodid;
        console.log('goodid:', goodid);
        //查询出在itemDetails中是否存在
        var alreadyExistsElements = $('#itemDetails').find('[goodid="' + goodid + '"]');
        if (alreadyExistsElements.length > 0) {
            console.log('已经存在:', goodid);
            //暂时先简单的做
            alert('已经添加了该商品');
        } else {
            var template = $("#template").html();
            var rendered = Mustache.render(template, combineObj);
            $('#itemDetails').append(rendered);
            calcalateAll();
        }
    };

    //动态添加时间 也就是添加明细后的事件
    $('#itemDetails tr input[name="good_num"]').live('change', function () {
        $('#submitBtn').attr('diabled', 'diabled');
        var current = $(this);
        var val = current.val();
        var maxnum = current.attr('maxnum');
        console.log('maxnum:', maxnum);
        //若大于设定的最大值 则直接设置为1
        if (parseInt(val) > parseInt(maxnum)) {
            val = 1;
            current.val(1);
        }
        //找到行
        var row = current.parent().parent();
        var tdArr = row.find('td');
        var price = tdArr.eq(3).text();
        //验证价格
        if (!/^[1-9]\d*$/.test(val)) {
            tdArr.eq(6).html('<strong>' + price + '</strong>');
        } else {
            //计算单个价格
            tdArr.eq(6).html('<strong>' + (price * val).toFixed(2) + '</strong>');
        }
        calcalateAll();
        //计算所有的价格
        $('#submitBtn').removeAttr('diabled');
    });

    //删除按钮,也就是动态删除相关的事件
    $('#itemDetails tr  a[datatype="delgood"]').live('click', function () {
        $('#submitBtn').attr('diabled', 'diabled');
        $(this).parent().parent().remove();
        calcalateAll();
        $('#submitBtn').removeAttr('diabled');
    });

    //提交相关的数据时的动作
    $('#submitBtn').click(function () {
        var monthplanName = $('#monthplanName').val();
        var departmentId = $('#departmentId').val();
        var priceSum = $('#price_sum').text();
        var month = $('#month').val();
        var year = $('#year').val();
        if ($.trim(monthplanName) == '') {
            alert('年度计划名称不能为空!');
            return;
        }
        if ($.trim(departmentId) == '') {
            alert('部门编号不能为空!');
            return;
        }
        //组装数据
        var postData = {};
        postData['monthplanName'] = monthplanName;
        postData['departmentId'] = departmentId;
        //每一个节点
        var items = new Array();
        $('#itemDetails tr').each(function () {
            var currentRow = $(this);
            var monthPlanItem = new Object();
            var inputArr = currentRow.find('input');
            inputArr.each(function (i, inputEle) {
                var name = $(inputEle).attr('name');
                var val = $(inputEle).val();
                monthPlanItem[name] = val;
            });
            items.push(monthPlanItem);
        });
        postData['items'] = items;
        postData['priceSum'] = parseFloat(priceSum).toFixed(2);
        postData['year'] = year;
        postData['month'] = month;

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "/monthplans/add",
            data: {
                'monthPlanData': JSON.stringify(postData) //stringify是在Ecma5也就是2011定义的
            },
            success: function (msg) {
                if (msg.code == '0') {
                    //返回列表页面
                    alert('保存成功');
                    $('#monthPlanId').val(msg.monthPlanId);
                    //    window.location.href = '/monthplans'; 不跳转
                } else if (msg.code == '1') {
                    alert('您所在的部门已经添加了年度计划，请你回列表查看');
                }
                else {
                    alert('添加异常，请联系开发者!');
                }
            }
        });
    });

});